package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Commoditys;
import com.example.springboot.mapper.CommoditysMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@RestController
@RequestMapping("/commoditys")
public class CommoditysController {

    /**
     * @RequestBody将传来的对象转化为JSON
     */
    @Resource
    private CommoditysMapper commoditysMapper;

    @GetMapping("/{id}")
    public Result<?> select(@PathVariable Long id){
        Commoditys commoditys =  commoditysMapper.selectById(id);
        return Result.success(commoditys);
    }


    /**
     * 新增
     */
    @PostMapping
    public Result<?> save(@RequestBody Commoditys commoditys) {
        commoditysMapper.insert(commoditys);
        return Result.success();
    }

    /**
     * 编辑
     */
    @PutMapping
    public Result<?> update(@RequestBody Commoditys commoditys) {
        commoditysMapper.updateById(commoditys);
        return Result.success();
    }

    /**
     * 删除
     * "/{id}"这种占位符数据获取需要@PathVariable注解来实现
     * "/{id}/{aa}"  @PathVariable Long id ,@PathVariable String aa 就可以取到两个值
     */
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        commoditysMapper.deleteById(id);
        return Result.success();
    }


    /**
     * 分页模糊查询
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "5") Integer pageSize,
//                              @RequestParam(defaultValue = "" ) Integer counts,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Commoditys> wrapper = Wrappers.<Commoditys>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Commoditys::getId, search);
        }
        Page<Commoditys> commoditysPage = commoditysMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(commoditysPage);
    }
}
